﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SQLite;

/// <summary>
///MYSQLHelper 的摘要说明
/// </summary>
public abstract class SQLiteM
{

    //数据库连接字符串
    //public static string connectionString = "Database=salarytest;Data Source=localhost;User Id=root;Password=root;pooling=false;CharSet=utf8;port=3306"; // test
    public static string connectionString = "Data Source=test.db;"; // server

    //public static string connectionString = "Database=salary;Data Source=192.168.1.209;User Id=root;Password=root;pooling=false;CharSet=utf8;port=3306";
    //public static string connectionString = "Database=salary;Data Source=127.0.0.1;User Id=root;Password=root;pooling=false;CharSet=utf8;port=3306"; // 本地
    //public static string connectionString = "Database=salary2;Data Source=127.0.0.1;User Id=root;Password=root;pooling=false;CharSet=utf8;port=3306";
    //public static string connectionString = "Database=salarycalculation;Data Source=192.168.1.36;User Id=root;Password=root;pooling=false;CharSet=utf8;port=3306";

    // 用于缓存参数的HASH表
    private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

    /// <summary>
    ///  给定连接的数据库用假设参数执行一个sql命令（不返回数据集）
    /// </summary>
    /// <param name="connectionString">一个有效的连接字符串</param>
    /// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
    /// <param name="cmdText">存储过程名称或者sql命令语句</param>
    /// <param name="commandParameters">执行命令所用参数的集合</param>
    /// <returns>执行命令所影响的行数</returns>
    public static int ExecuteNonQuery(CommandType cmdType, string cmdText, params SQLiteParameter[] commandParameters)
    {
        
        SQLiteCommand cmd = new SQLiteCommand();

        using (SQLiteConnection conn = new SQLiteConnection(connectionString))
        {
            PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }
    }

    /// <summary>
    /// 获取数据库连接对象
    /// </summary>
    /// <returns>数据库连接对象</returns>
    public static SQLiteConnection GetConnection()
    {
        SQLiteConnection conn = new SQLiteConnection(connectionString);
        return conn;
    }


    /// <summary>
    /// 用现有的数据库连接执行一个sql命令（不返回数据集）
    /// </summary>
    /// <param name="connection">一个现有的数据库连接</param>
    /// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
    /// <param name="cmdText">存储过程名称或者sql命令语句</param>
    /// <param name="commandParameters">执行命令所用参数的集合</param>
    /// <returns>执行命令所影响的行数</returns>
    public static int ExecuteNonQuery(SQLiteConnection connection, CommandType cmdType, string cmdText, params SQLiteParameter[] commandParameters)
    {

        SQLiteCommand cmd = new SQLiteCommand();

        PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
        int val = cmd.ExecuteNonQuery();
        cmd.Parameters.Clear();
        return val;
    }

    /// <summary>
    ///使用现有的SQL事务执行一个sql命令（不返回数据集）
    /// </summary>
    /// <remarks>
    ///举例:
    ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SQLiteParameter("@prodid", 24));
    /// </remarks>
    /// <param name="trans">一个现有的事务</param>
    /// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
    /// <param name="cmdText">存储过程名称或者sql命令语句</param>
    /// <param name="commandParameters">执行命令所用参数的集合</param>
    /// <returns>执行命令所影响的行数</returns>
    public static int ExecuteNonQuery(SQLiteTransaction trans, CommandType cmdType, string cmdText, params SQLiteParameter[] commandParameters)
    {
        SQLiteCommand cmd = new SQLiteCommand();
        PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
        int val = cmd.ExecuteNonQuery();
        cmd.Parameters.Clear();
        return val;
    }

    /// <summary>
    /// 用执行的数据库连接执行一个返回数据集的sql命令
    /// </summary>
    /// <remarks>
    /// 举例:
    ///  SQLiteDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SQLiteParameter("@prodid", 24));
    /// </remarks>
    /// <param name="connectionString">一个有效的连接字符串</param>
    /// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
    /// <param name="cmdText">存储过程名称或者sql命令语句</param>
    /// <param name="commandParameters">执行命令所用参数的集合</param>
    /// <returns>包含结果的读取器</returns>
    public static SQLiteDataReader ExecuteReader(CommandType cmdType, string cmdText, params SQLiteParameter[] commandParameters)
    {
        //创建一个SQLiteCommand对象
        SQLiteCommand cmd = new SQLiteCommand();
        //创建一个SQLiteConnection对象
        SQLiteConnection conn = new SQLiteConnection(connectionString);

        //在这里我们用一个try/catch结构执行sql文本命令/存储过程，因为如果这个方法产生一个异常我们要关闭连接，因为没有读取器存在，
        //因此commandBehaviour.CloseConnection 就不会执行
        try
        {
            //调用 PrepareCommand 方法，对 SQLiteCommand 对象设置参数
            PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
            //调用 SQLiteCommand  的 ExecuteReader 方法
            SQLiteDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            //清除参数
            cmd.Parameters.Clear();
            return reader;
        }
        catch
        {
            //关闭连接，抛出异常
            conn.Close();
            throw;
        }
    }

    /// <summary>
    /// 返回DataSet
    /// </summary>
    /// <param name="connectionString">一个有效的连接字符串</param>
    /// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
    /// <param name="cmdText">存储过程名称或者sql命令语句</param>
    /// <param name="commandParameters">执行命令所用参数的集合</param>
    /// <returns></returns>
    public static DataSet GetDataSet(CommandType cmdType, string cmdText, params SQLiteParameter[] commandParameters)
    {
        //创建一个SQLiteCommand对象
        SQLiteCommand cmd = new SQLiteCommand();
        //创建一个SQLiteConnection对象
        SQLiteConnection conn = new SQLiteConnection(connectionString);

        //在这里我们用一个try/catch结构执行sql文本命令/存储过程，因为如果这个方法产生一个异常我们要关闭连接，因为没有读取器存在，

        try
        {
            //调用 PrepareCommand 方法，对 SQLiteCommand 对象设置参数
            PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
            //调用 SQLiteCommand  的 ExecuteReader 方法
            SQLiteDataAdapter adapter = new SQLiteDataAdapter();
            adapter.SelectCommand = cmd;
            DataSet ds = new DataSet();

            adapter.Fill(ds);
            //清除参数
            cmd.Parameters.Clear();
            conn.Close();
            return ds;
        }
        catch (Exception e)
        {
            throw e;
        }
    }



    /// <summary>
    /// 用指定的数据库连接字符串执行一个命令并返回一个数据集的第一列
    /// </summary>
    /// <remarks>
    ///例如:
    ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SQLiteParameter("@prodid", 24));
    /// </remarks>
    ///<param name="connectionString">一个有效的连接字符串</param>
    /// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
    /// <param name="cmdText">存储过程名称或者sql命令语句</param>
    /// <param name="commandParameters">执行命令所用参数的集合</param>
    /// <returns>用 Convert.To{Type}把类型转换为想要的 </returns>
    public static object ExecuteScalar(CommandType cmdType, string cmdText, params SQLiteParameter[] commandParameters)
    {
        SQLiteCommand cmd = new SQLiteCommand();

        using (SQLiteConnection connection = new SQLiteConnection(connectionString))
        {
            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }
    }

    /// <summary>
    /// 用指定的数据库连接执行一个命令并返回一个数据集的第一列
    /// </summary>
    /// <remarks>
    /// 例如:
    ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SQLiteParameter("@prodid", 24));
    /// </remarks>
    /// <param name="connection">一个存在的数据库连接</param>
    /// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
    /// <param name="cmdText">存储过程名称或者sql命令语句</param>
    /// <param name="commandParameters">执行命令所用参数的集合</param>
    /// <returns>用 Convert.To{Type}把类型转换为想要的 </returns>
    public static object ExecuteScalar(SQLiteConnection connection, CommandType cmdType, string cmdText, params SQLiteParameter[] commandParameters)
    {


        SQLiteCommand cmd = new SQLiteCommand();

        PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
        object val = cmd.ExecuteScalar();
        cmd.Parameters.Clear();
        return val;
    }

    /// <summary>
    /// 插入信息，并返回新插入记录的id
    /// </summary>
    /// <param name="cmdType"></param>
    /// <param name="cmdText"></param>
    /// <returns>id</returns>
    public static object ExecuteInsert(CommandType cmdType, string cmdText)
    {
        SQLiteCommand cmd = new SQLiteCommand();

        using (SQLiteConnection connection = new SQLiteConnection(connectionString))
        {
            PrepareCommand(cmd, connection, null, cmdType, cmdText, null);
            cmd.ExecuteScalar();
            cmd.Parameters.Clear();

            PrepareCommand(cmd, connection, null, CommandType.Text, "select last_insert_rowid()", null);
            object val = cmd.ExecuteScalar();
            return val;
        }
    }

    /// <summary>
    /// 将参数集合添加到缓存
    /// </summary>
    /// <param name="cacheKey">添加到缓存的变量</param>
    /// <param name="commandParameters">一个将要添加到缓存的sql参数集合</param>
    public static void CacheParameters(string cacheKey, params SQLiteParameter[] commandParameters)
    {
        parmCache[cacheKey] = commandParameters;
    }

    /// <summary>
    /// 找回缓存参数集合
    /// </summary>
    /// <param name="cacheKey">用于找回参数的关键字</param>
    /// <returns>缓存的参数集合</returns>
    public static SQLiteParameter[] GetCachedParameters(string cacheKey)
    {
        SQLiteParameter[] cachedParms = (SQLiteParameter[])parmCache[cacheKey];

        if (cachedParms == null)
            return null;

        SQLiteParameter[] clonedParms = new SQLiteParameter[cachedParms.Length];

        for (int i = 0, j = cachedParms.Length; i < j; i++)
            clonedParms[i] = (SQLiteParameter)((ICloneable)cachedParms[i]).Clone();

        return clonedParms;
    }

    /// <summary>
    /// 准备执行一个命令
    /// </summary>
    /// <param name="cmd">sql命令</param>
    /// <param name="conn">OleDb连接</param>
    /// <param name="trans">OleDb事务</param>
    /// <param name="cmdType">命令类型例如 存储过程或者文本</param>
    /// <param name="cmdText">命令文本,例如:Select * from Products</param>
    /// <param name="cmdParms">执行命令的参数</param>
    private static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, SQLiteTransaction trans, CommandType cmdType, string cmdText, SQLiteParameter[] cmdParms)
    {

        if (conn.State != ConnectionState.Open)
            conn.Open();

        cmd.Connection = conn;
        cmd.CommandText = cmdText;

        if (trans != null)
            cmd.Transaction = trans;

        cmd.CommandType = cmdType;

        if (cmdParms != null)
        {
            foreach (SQLiteParameter parm in cmdParms)
                cmd.Parameters.Add(parm);
        }
    }

    /// <summary>
    /// 根据字段和对应的值构造Mysql参数列表
    /// </summary>
    /// <param name="field">字段数组</param>
    /// <param name="values">值数组</param>
    /// <returns>参数列表</returns>
    public static SQLiteParameter[] GetParams(string[] field, object[] values)
    {
        SQLiteParameter[] param = new SQLiteParameter[field.Length];
        for (int i = 0; i < field.Length; i++)
        {
            param[i] = new SQLiteParameter("?" + field[i], values[i]);
        }
        return param;
    }

}